<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.bloveambition.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com>
// +----------------------------------------------------------------------
namespace Common\Api;

/**
 * 公共接口类
 * 
 * @author derek <693472824@qq.com>
 */
class UtilApi
{

    /**
     * 将数组转换成树形结构的多维数组
     * 
     * @param array $list
     *            要转换的数据
     * @param string $pk
     *            主键字段
     * @param string $pid
     *            父节点ID
     * @param string $child
     *            子节点
     * @param string $root
     *            根节点ID
     * @return array $tree 多维数组
     * @author derek <693472824@qq.com>
     */
    public static function list_to_tree ($list, $pk = 'id', $pid = 'pid', $child = '_child', 
            $root = 0, $show = '')
    {
        $tree = array();
        
        if (is_array($list)) {
            foreach ($list as $key => $value) {
                
                $showStatus = ! empty($show) && isset($value[$show]) ? $value[$show] ==
                         '1' : true;
                
                if ($value[$pid] == $root && $showStatus) {
                    $tree[] = & $list[$key];
                    $list[$key][$child] = self::list_to_tree($list, $pk, $pid, 
                            $child, $value[$pk]);
                }
            }
        }
        
        return $tree;
    }

    /**
     * 取数组中指定元素的顶级节点
     * 
     * @param array $list
     *            数组
     * @param string $pk
     *            主键字段
     * @param string $pid
     *            父节点字段
     * @param string $child
     *            当前节点主键字段值
     * @param string $root
     *            根节点ID
     * @return string $superID 父节点为 $root 的顶级元素主键字段值
     * @author derek <693472824@qq.com>
     */
    public static function getSuperID ($list, $pk = 'id', $pid = 'pid', $currentID = null, 
            $root = 0)
    {
        if (empty($currentID) || $currentID == $root) {
            return $currentID;
        }
        
        foreach ($list as $k => $v) {
            
            if ($v[$pk] == $currentID) {
                if ($v[$pid] == $root) {
                    $superID = $v[$pk];
                } else {
                    $superID = self::getSuperID($list, $pk, $pid, $v[$pid], 
                            $root);
                }
                break;
            }
        }
        
        return $superID;
    }

    /**
     * 发送短信验证码
     * 
     * @param string $mobile
     *            手机号 多个用英文的逗号隔开
     * @param string $content
     *            发送短信内容
     * @author derek <693472824@qq.com>
     */
    public static function sendCode ($mobile, $content)
    {
        
        if(empty($mobile) || empty($content)){
            $this->error = '参数错误';
            return false;
        }
        
        $data['username'] = C('CONFIG_SMS_SN');
        $pwd = C('CONFIG_SMS_PWD');
        $key = C('CONFIG_SMS_KEY');
        $signature = C('CONFIG_SMS_SIGNATURE') ? : '帮工小哥';
        $data['time'] = time() - 8 * 3600;
        $data['mobile'] = $mobile;
        
        $data['content'] = urlencode($content.'【'.$signature.'】');
        $data['authkey'] = md5($data['username'].$data['time'].md5($pwd).$key);
        
        $url = 'http://sms.edmcn.cn/api/cm/trigger_mobile.php';
        
        $row = parse_url($url);
        $host = $row['host'];
        $port = isset($row['port']) ? $row['port']:80;
        $file = $row['path'];
        $post = '';
        
        while (list($k,$v) = each($data)) {
            $post .= $k."=".$v."&";
        }
        
        $post = substr( $post , 0 , -1 );
        $len = strlen($post);
        
        $fp = @fsockopen($host ,$port, $errno, $errstr, 10);
        
        if(!$fp){
            return "connect error";
        }
        
        $receive = '';
        $out = "POST $file HTTP/1.0\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: $len\r\n\r\n";
        $out .= $post;
        fwrite($fp, $out);
        while (!feof($fp)) {
            $receive .= fgets($fp, 128);
        }
        fclose($fp);
        $receive = explode("\r\n\r\n",$receive);
        unset($receive[0]);
        return implode("",$receive);
    }

    /**
     * 获取signature供上传图片用
     */
    public static function getSignature($nonceStr, $timeStamp, $url){
    
        $ticket = self::getTicket();
    
        $data['noncestr'] = $nonceStr;
        $data['jsapi_ticket'] = $ticket;
        $data['timestamp'] = $timeStamp;
        $data['url'] = $url;
    
        ksort($data);
        $temp = '';
    
        foreach ($data as $key=>$val){
    
            $temp = $temp ? $temp.'&'.$key.'='.$val : $key.'='.$val;
        }
    
        $signature = sha1($temp);
    
        return $signature;
    }
    
    /**
     * 获取 jsapi_ticket
     */
    public static function getTicket(){
    
        $ticket = S('JSAPI_TICKET');
    
        if(empty($ticket)){
    
            $accessToken = S('ACCESS_TOKEN');
    
            if(empty($accessToken)){
    
                $accessToken = self::getToken();
            }
    
            $path = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
            $param = 'access_token='.$accessToken.'&type=jsapi';
    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $path);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
            $dataStr = curl_exec($ch);
            curl_close($ch);
    
            $data = json_decode($dataStr, true);
    
            if($data['ticket']){
    
                $ticket = $data['ticket'];     //access_token值
                $expires = $data['expires_in'];     //微信服务器返回的 access_token 默认有效期
    
                S('JSAPI_TICKET', $ticket, $expires-1);
    
                return $ticket;
            }else{
                return '';
            }
        }else{
    
            return $ticket;
        }
    
    }
    
    /**
     * 获取 access_token
     */
    public function getToken(){
    
        $token = S('ACCESS_TOKEN');
    
        if(empty($token)){
            $appID = C('WxPayConf_pub.APPID');
            $secret = C('WxPayConf_pub.APPSECRET');
    
            $path = 'https://api.weixin.qq.com/cgi-bin/token';
            $param = 'grant_type=client_credential&appid='.$appID.'&secret='.$secret;
    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $path);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
            $dataStr = curl_exec($ch);
            curl_close($ch);
    
            $data = json_decode($dataStr, true);
    
            if($data['access_token']){
    
                $token = $data['access_token'];     //access_token值
                $expires = $data['expires_in'];     //微信服务器返回的 access_token 默认有效期
    
                S('ACCESS_TOKEN', $token, $expires-1);
    
                return $token;
            }else{
    
                return '';
            }
        }else{
    
            return S('ACCESS_TOKEN');
        }
    }
    
    /**
     * 发送极光推送消息
     *
     * @param string $alias
     *            单个别名字符串或多个别名组成的数组
     * @param string $tag
     *            单个标签字符串或多个标签组成的数组
     * @param string $extra
     *            自定义消息休
     * @author derek <693472824@qq.com>
     */
    public static function jPush ($alias, $tag, $extra) {
        
        // 引入WxPayPubHelper
        vendor('JPush.JPush');
        
        //1：系统通知；2：撤单；3：抢单；5：小哥转单；6：客服转单；7：站长派单消息；8：用户指定小哥推送消息
        if($extra['msg_type'] == '1'){
            $alert = $extra['content'];
        }elseif ($extra['msg_type'] == '2'){
            $alert = $extra['content'];
        }elseif ($extra['msg_type'] == '3'){
            $alert = '抢单成功，订单号：'.$extra['order_no'];
        }elseif($extra['msg_type'] == '4'){
            $alert = '用户新下订单，订单号：'.$extra['order_no'];
        }elseif (in_array($extra['msg_type'], array('5','6'))){
            $alert = '您有一条新转单';
        }elseif (in_array($extra['msg_type'], array('7','8'))){
            $alert = '您有一条新派单';
        }
        
        $key = C('JPUSH_APPKEY');
        $secret = C('JPUSH_MASTER_SECRET');
        
        // 初始化
        $client = new \JPush($key, $secret);
        
        try {
            $result = $client->push()
                    ->setPlatform(array('android'))
                    ->addAlias($alias)
                    ->addTag($tag)
                    ->setNotificationAlert($alert)
                    ->addAndroidNotification($alert, '', 1, $extra)
                    ->send();
        } catch (\APIRequestException $e) {
        
        }
        
                    
        return $result;
    }
    
}